package com.siss.tenancy.util;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 李宜朋
 * @ClassName HeaderUtil
 * @Description 根据url获取header参数
 * @date 2020/8/11 16:00
 * @Version 2.0
 */
public class HeaderUtil {

    static Logger logger = LoggerFactory.getLogger(HeaderUtil.class);

    public static String getCookie(String url)throws Exception{
        Connection.Response res = Jsoup.connect(url).timeout(30000).execute();
        Map<String, String> cookies = new HashMap<>(res.cookies());
        if(null != cookies){
            return cookies.keySet().stream().map(e ->  e+cookies.get(e)).collect(Collectors.joining(";"));
        }
        return null;
    }

    public static String sendPostAndCookies(String url, String param,String charset,String cookie,String contentType) {
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            if(!StringUtil.isEmpty(cookie)){
                conn.setRequestProperty("Cookie", cookie);
            }
            // 设置通用的请求属性
            conn.setRequestProperty("Content-type",contentType);
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setRequestProperty("contentType", charset);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 当outputStr不为null时向输出流写数据
            if (null != param) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(param.getBytes(charset));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            logger.info(buffer.toString());
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void main(String[] args)throws Exception {
        String cookie = getCookie("http://xhzhglxt.cirea.org.cn/website/gjs_Iframe.asp");
        System.out.println(cookie);
        String postUrl = "http://xhzhglxt.cirea.org.cn/website/gjss_cx.asp";
        String contentType = "application/x-www-form-urlencoded";
        String radio=  "Radio=Appraiser&";
        String name = "施丽星";
        StringBuilder builder = new StringBuilder();
        builder.append(radio);
        builder.append("name="+name);
        System.out.println(builder.toString());
        String str = sendPostAndCookies(postUrl,builder.toString(),"GB2312",cookie,contentType);
        System.out.println(str);
        Document htmlStr= Jsoup.parse(str);
        Element postItems = htmlStr.getElementById("Table2");
        System.out.println(postItems);
        Elements elements = postItems.getElementsByClass("gjlist");
        elements.forEach(e -> logger.debug(e.text()));
    }


}
